package net.mlike.openssp.server.entity.system;

import net.mlike.openssp.server.entity.BaseEntity;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotEmpty;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by wallellen@hotmail.com on 5/24/18.
 */
@Entity
@Table(name = "t_sys_user")
public class User extends BaseEntity {
    @NotEmpty(message = "用户名不能为空")
    private String username;

    private String password;

    private String salt;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "t_sys_user_role",
        joinColumns = {@JoinColumn(name = "user_id")},
        inverseJoinColumns = {@JoinColumn(name = "role_id")})
    private List<Role> roles;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    @Transient
    public Set<String> getAllRoles() {
        Set<String> roles = new HashSet<>();

        if (this.roles == null) {
            return roles;
        }

        this.roles.forEach(r -> roles.add(r.getCode()));

        return roles;
    }

    @Transient
    public Set<String> getAllMenus() {
        Set<String> menus = new HashSet<>();

        if (roles == null) {
            return menus;
        }

        roles.forEach(r -> menus.addAll(r.getAllMenus()));

        return menus;
    }
}
